import React, { Component } from 'react';
import { Tools, List, Radio } from 'weaver-mobile';

const RadioItem = Radio.RadioItem;
const { getLabel, callApi, getLocaleLabel } = Tools;
const getUserLanguage = () => window.e9_locale ? window.e9_locale.userLanguage : 7;

export default class Demo extends Component {
  state = {
    activeLanguageInfo: [],
    activeLanguageIds: [],
    languageIdentify: [],
    systemDefaultLang: {},
  };

  componentDidMount() {
    callApi({ url: '/api/system/language/base/getActiveLanguage' }).then(res => {
      if (res.status === '1') {
        this.setState(res);
      }
    });
  }

  render() {
    const value = getUserLanguage();
    const { activeLanguageInfo, systemDefaultLang } = this.state;
    const defaultKey = Object.keys(systemDefaultLang)[0] || '';
    return (
      <div className='wm-change-lang'>
        <List renderHeader={() => getLabel(18214, '请选择')}>
          {
            activeLanguageInfo.map(l => (
              <RadioItem
                key={l.id}
                checked={value.toString() === l.id}
                onChange={() => this.handleChange(l.id)}
              >
                {l.language}
                {defaultKey.toString() === l.id ? ` (${getLabel(28119, '系统默认').replace(/\s/g, '')})` : ''}
              </RadioItem>
            ))
          }
        </List>
      </div>
    );
  }

  handleChange = (languageId) => {
    callApi({ url: '/api/system/language/base/changeLang', params: { languageId } }).then(res => {
      if (res.status === '1') {
        window.e9_locale = undefined;
        getLocaleLabel('common', () => {
          // window.location.reload();
          this.forceUpdate();
        });
      }
    });
  }
}
